package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.leyou.common.exception.LyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPay wxPay;

    @Autowired
    private WXPayConfigImpl payConfig;

    public String createWxPayUrl(Long orderId, Long actualFee){
        log.info("【微信统一下单】获取支付链接开始！");
        // 请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "乐优支付");
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", actualFee.toString());
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", payConfig.getNotifyUrl());
        data.put("trade_type", payConfig.getPayType());  // 此处指定为扫码支付

        try {
            Map<String, String> resp = wxPay.unifiedOrder(data);
            //验证通信标识和业务标识
            checkWxReturnCode(resp);
            log.info("【微信统一下单】获取支付链接正常结束！");
            return resp.get("code_url");
        } catch (Exception e) {
            log.info("【微信统一下单】获取支付链接异常！");
            throw new LyException(502, "【微信统一下单】获取支付链接异常！");
        }
    }

    /**
     * 验证通信标识和业务标识
     * @param resp
     */
    public void checkWxReturnCode(Map<String, String> resp) {
        if(!resp.get("return_code").equals("SUCCESS")){
            log.info("【微信统一下单】获取支付链接通信异常！");
            throw new LyException(502, "【微信统一下单】获取支付链接通信异常！");
        }
        if(!resp.get("result_code").equals("SUCCESS")){
            log.info("【微信统一下单】获取支付链接业务异常！错误信息为：{}",resp.get("err_code_des"));
            throw new LyException(502, "【微信统一下单】获取支付链接业务异常！");
        }
    }

}
